package com.bamanker.cloudconsumer.handler;

import com.bamanker.cloudapi.model.error.CommonErrorCode;
import com.bamanker.cloudapi.model.exception.BusinessException;
import com.bamanker.cloudapi.model.response.Result;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;

import java.util.stream.Collectors;


/**
 * @author bamanker
 *
 * 统一异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 通用异常处理方法
     **/
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result error(Exception e, WebRequest request) {
        log.error("error:{}",e.getMessage());
        return Result.buildFailure(CommonErrorCode.UNKNOWN_ERROR,request.getDescription(true));
    }



    /**
     * 处理 form data方式调用接口对象参数校验失败抛出的异常
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Result bindExceptionHandler(BindException e) {
        String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
        return Result.buildFailure(CommonErrorCode.INVALID_ARGUMENT.getCode(),message);
    }

    /**
     * 处理Get请求中 验证路径中 单个参数请求失败抛出异常
     * @param e
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result constraintViolationExceptionHandler(ConstraintViolationException e) {
        String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining());
        return Result.buildFailure(CommonErrorCode.INVALID_ARGUMENT.getCode(),message);
    }


    /**
     * 处理 json 请求体调用接口对象参数校验失败抛出的异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result jsonParamsException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String msg=";";

        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            msg = String.format("%s%s；", fieldError.getField(), fieldError.getDefaultMessage())+msg;
        }
        return Result.buildFailure(CommonErrorCode.INVALID_ARGUMENT.getCode(),msg);
    }

    /**
     * 自定义异常处理方法
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public Result error(BusinessException e) {
        log.error("error:{}",e.getMessage());
        return Result.buildFailure(e.getMessage(),e.getResultCode().getCode());
    }

}
